import requests
import execjs
from datetime import datetime, timezone, timedelta
import pandas as pd
import os
import time
import random
import threading
from queue import Queue
import concurrent.futures

# 创建文件写入锁
zhuanli_lock = threading.Lock()
rjzzq_lock = threading.Lock()

cookies = {
    'qcc_did': '9769dcda-2771-4c6f-8337-04106e605eab',
    'UM_distinctid': '196e72bd22a5b6-09784da5b5a60c8-26011f51-144000-196e72bd22b1eea',
    'QCCSESSID': '80e6aafe420ea3ea5126f112e3',
    'tfstk': 'gcCIB2fDqDmQwEA-Pp4Z1kh19uA5dPPqV4TRoahEyBdK20Qvbe5UxaK5VG-iY9yl4gi5YGSWEyxy23sPy9zagS7h-QARVoP4gIoHK7IIvHhLyFLJPP8L2PqZYQA80lJCMt4MZMU-xFIRWPTyzXKR2Lp9WhYqvQKpecH9khdJwppK65LyrvHJJvU1WhYJw3IJwPO9jUH9UlTgdHQQ87q4PJgiDw-swbC6WuYcRycW76YBdnQdObh-ke9BDwK_v7P4ZdQkF_0oNL7dngYAvDEWq1_O9tIYbv-dhU_VFiUrKFJ5tCtR9S0XX6_51pXZvvLXOH9A9KF7lZpRC1OF9uDc7NtphCWaIkJyOM6Dmpegjg_6YgCBBDZw4t7N9dsYbfskFTCe66ETGg7SgnagWYg6nbT60PasEYqQ1sCOKW0wVpLM7sz_5DMkpFY60PasEYvpSFJa5PiIE',
    'acw_tc': '0a472f8417494335426987235e006ce80c14cf0e6abba924437639a0ab2fea',
    'CNZZDATA1254842228': '942005259-1747635131-https%253A%252F%252Fwww.baidu.com%252F%7C1749433543',
}
with open('./get_header.js', 'r', encoding='utf-8') as f:
    js_code = f.read()
ctx = execjs.compile(js_code)


def get_proxy():
    proxy = requests.get("http://127.0.0.1:5010/get/").json()
    print(f"使用代理IP: {proxy.get('proxy')}")
    return proxy


def delete_proxy(proxy):
    requests.get("http://127.0.0.1:5010/delete/?proxy={}".format(proxy))


# 获取软件著作权字段信息
def get_rjzzquandata(data):
    items = []
    for i in range(10):
        try:
            rjzzqlist = []
            Owner = data['data'][i]['Owner']
            Name = data['data'][i]['Name']
            ShortName = data['data'][i]['ShortName']
            VersionNo = data['data'][i]['VersionNo']
            RegisterNo = data['data'][i]['RegisterNo']
            try:
                DevelopDate = datetime.fromtimestamp(
                    int(data['data'][i]['DevelopDate']), tz=timezone.utc)
                adjusted_date = DevelopDate + timedelta(hours=8)
                formatted_time = adjusted_date.strftime("%Y-%m-%d ")
                DevelopDate = formatted_time
            except:
                DevelopDate = '-'
            try:
                PublishDate = datetime.fromtimestamp(
                    int(data['data'][i]['PublishDate']), tz=timezone.utc)
                adjusted_date = PublishDate + timedelta(hours=8)
                formatted_time = adjusted_date.strftime("%Y-%m-%d ")
                PublishDate = formatted_time
            except:
                PublishDate = '-'
            try:
                RegisterAperDate = datetime.fromtimestamp(
                    int(data['data'][i]['RegisterAperDate']), tz=timezone.utc)
                adjusted_date = RegisterAperDate + timedelta(hours=8)
                formatted_time = adjusted_date.strftime("%Y-%m-%d ")
                RegisterAperDate = formatted_time
            except:
                RegisterAperDate = '-'
            Acquireway = data['data'][i]['Acquireway']
            rjzzqlist.extend(
                [Owner, Name, ShortName, VersionNo, RegisterNo, DevelopDate, PublishDate, RegisterAperDate, Acquireway])
            items.append(rjzzqlist)
        except:
            return items
    return items


# 软件著作权信息追加
def write_csv_rjzzq(items):
    """软件著作权信息追加"""
    with rjzzq_lock:  # 使用锁保护文件写入
        file_exists = os.path.exists('./ruanjian.csv')
        df = pd.DataFrame(items, columns=['公司名称', '软件全称', '软件简称', '版本号', '登记号', '开发完成日期',
                                          '首次发布日期', '等级日期', '权力取得方式'])
        df.to_csv('ruanjian.csv', mode='a',
                  index=False, header=not file_exists)
        if not file_exists:
            print("创建新文件并写入表头和数据")
        else:
            print("数据已追加到 ruanjian.csv")

# 获取专利字段信息


def get_zhuanlidata(data):
    items = []
    for i in range(10):
        try:
            zhuanlilist = []
            AssigneeList = data['data'][i]['AssigneeList']
            titofint = data['data'][i]['Title']
            KindCodeDesc = data['data'][i]['KindCodeDesc']
            LegalStatusDesc = data['data'][i]['LegalStatusDesc']
            ApplicationNumber = data['data'][i]['ApplicationNumber']
            Application_date = datetime.fromtimestamp(
                int(data['data'][i]['ApplicationDate']), tz=timezone.utc)
            adjusted_date = Application_date + timedelta(hours=8)
            formatted_time = adjusted_date.strftime("%Y-%m-%d ")
            Application_date = formatted_time
            PublicationNumber = data['data'][i]['PublicationNumber']
            LegalStatusDate = datetime.fromtimestamp(
                int(data['data'][i]['LegalStatusDate']), tz=timezone.utc)
            adjusted_date = LegalStatusDate + timedelta(hours=8)
            formatted_time = adjusted_date.strftime("%Y-%m-%d ")
            LegalStatusDate = formatted_time
            inventor = data['data'][i]['InventorList']
            zhuanlilist.extend([AssigneeList, titofint, KindCodeDesc, LegalStatusDesc, ApplicationNumber,
                                Application_date, PublicationNumber, LegalStatusDate, inventor])
            items.append(zhuanlilist)
        except:
            return items
    return items

# 专利信息追加写入elex文件中


def write_csv_zhuanli(items):
    """专利信息追加写入csv文件中"""
    with zhuanli_lock:  # 使用锁保护文件写入
        file_exists = os.path.exists('./zhuanli.csv')
        df = pd.DataFrame(items, columns=['公司名称', '发明名称', '专利类型', '法律状态', '申请号', '申请日期',
                                          '公开号', '公开日期', '发明人'])
        df.to_csv('zhuanli.csv', mode='a',
                  index=False, header=not file_exists)
        if not file_exists:
            print("创建新文件并写入表头和数据")
        else:
            print("数据已追加到 zhuanli.csv")


def start_zhunali(keyno):
    # 专利信息的获取
    for i in range(1, 500):
        e = "/api/datalist/zhuanlilist"
        h = '6ca89496347558e73150654b24e37811'
        json_data = {
            'keyNo': keyno,
            'pageIndex': i,
            'isNewAgg': True,
        }
        header1 = ctx.call('get_i', e, json_data)
        header2 = ctx.call('get_u', e, json_data, h)
        headers = {
            header1: header2,
            'accept': 'application/json, text/plain, */*',
            'accept-language': 'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6',
            'content-type': 'application/json',
            'origin': 'https://www.qcc.com',
            'priority': 'u=1, i',
            # 'referer': 'https://www.qcc.com/cassets/6b242b475738f45a4dd180564d029aa9.html',
            'sec-ch-ua': '"Google Chrome";v="137", "Chromium";v="137", "Not/A)Brand";v="24"',
            'sec-ch-ua-mobile': '?0',
            'sec-ch-ua-platform': '"Windows"',
            'sec-fetch-dest': 'empty',
            'sec-fetch-mode': 'cors',
            'sec-fetch-site': 'same-origin',
            'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/137.0.0.0 Safari/537.36',
            'x-pid': 'd7f7e672b425f0b5418b3f6ee9da2ec7',
            'x-requested-with': 'XMLHttpRequest',
            # 'cookie': 'qcc_did=043f26a4-6fb4-4968-ae84-ef0ca6779d79; UM_distinctid=196ec5fd5a09e7-0ce8ec88feb166-26011f51-144000-196ec5fd5a11ab7; QCCSESSID=3596e42eb3e44679d31da52bb7; tfstk=g2aqMLYLjZQVRqDxmzgwYBaRJL3xPVWB7PMss5ViGxDDlE9g45wTlcXxlPyrkzZX5x6x752I796CRwNYMq3Gd9w4lH4s-jJmsdi0Z40s_LZ1pGNYMVd-gJVLBSdZEhkZSV2ir0ci6VYMoxfPrXDkofYmsLfreYcMImxmEUcxtIx0IVfzZYhiSA2im_PoBlMidUlEm1_6hA2pM6mjKSDySeRKgmA_ghTH-Phq0PVmUSP4zjoqKc0wQnz0F54bk0IJVVF7YRrgKTtjnklUUDZVLEyUHf2rlyfOD0ng7Pl82O-ZLlVbvlmPiZVruxorgmR2jqrgHPoY0CCLZq28vvnc2ThzlyiZp0Jln7NrnDrahTLihkPuUDaWFeg3v8zZx2jPTdhowvzT0dxZmbhrd_5zOIsvAzZAs8-9XmE-av1AMhKtmbhrd_5yXhnxJbkCMsC..; CNZZDATA1254842228=882588239-1747722426-%7C1749089636; acw_tc=1a0c39d317491038550071446e006ea2525ded8a7dd6512bc9152497e74d5c',
        }
        try:
            response = requests.post('https://www.qcc.com/api/datalist/zhuanlilist',
                                     cookies=cookies, headers=headers, json=json_data)
            time.sleep(random.uniform(1, 5))
        except:
            break
        if response.text != 'null':
            pass
        else:
            break
        data = response.json()
        if data['data'] == []:
            print(f'第{i}页没有专利信息')
            break
        zhuanli_data = get_zhuanlidata(data)
        write_csv_zhuanli(zhuanli_data)


def start_rjzzq(keyno):
    # 软件著作权的获取
    for i in range(1, 500):
        stop_outer = False
        e = "/api/datalist/rjzzqlist"
        h = '6ca89496347558e73150654b24e37811'
        json_data = {
            'keyNo': keyno,
            'pageIndex': i,
            'isNewAgg': True,
        }
        header1 = ctx.call('get_i', e, json_data)
        header2 = ctx.call('get_u', e, json_data, h)
        headers = {
            header1: header2,
            'accept': 'application/json, text/plain, */*',
            'accept-language': 'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6',
            'content-type': 'application/json',
            'origin': 'https://www.qcc.com',
            'priority': 'u=1, i',
            # 'referer': 'https://www.qcc.com/cassets/6b242b475738f45a4dd180564d029aa9.html',
            'sec-ch-ua': '"Google Chrome";v="137", "Chromium";v="137", "Not/A)Brand";v="24"',
            'sec-ch-ua-mobile': '?0',
            'sec-ch-ua-platform': '"Windows"',
            'sec-fetch-dest': 'empty',
            'sec-fetch-mode': 'cors',
            'sec-fetch-site': 'same-origin',
            'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/137.0.0.0 Safari/537.36',
            'x-pid': 'd7f7e672b425f0b5418b3f6ee9da2ec7',
            'x-requested-with': 'XMLHttpRequest',
            # 'cookie': 'qcc_did=043f26a4-6fb4-4968-ae84-ef0ca6779d79; UM_distinctid=196ec5fd5a09e7-0ce8ec88feb166-26011f51-144000-196ec5fd5a11ab7; QCCSESSID=3596e42eb3e44679d31da52bb7; tfstk=g2aqMLYLjZQVRqDxmzgwYBaRJL3xPVWB7PMss5ViGxDDlE9g45wTlcXxlPyrkzZX5x6x752I796CRwNYMq3Gd9w4lH4s-jJmsdi0Z40s_LZ1pGNYMVd-gJVLBSdZEhkZSV2ir0ci6VYMoxfPrXDkofYmsLfreYcMImxmEUcxtIx0IVfzZYhiSA2im_PoBlMidUlEm1_6hA2pM6mjKSDySeRKgmA_ghTH-Phq0PVmUSP4zjoqKc0wQnz0F54bk0IJVVF7YRrgKTtjnklUUDZVLEyUHf2rlyfOD0ng7Pl82O-ZLlVbvlmPiZVruxorgmR2jqrgHPoY0CCLZq28vvnc2ThzlyiZp0Jln7NrnDrahTLihkPuUDaWFeg3v8zZx2jPTdhowvzT0dxZmbhrd_5zOIsvAzZAs8-9XmE-av1AMhKtmbhrd_5yXhnxJbkCMsC..; CNZZDATA1254842228=882588239-1747722426-%7C1749089636; acw_tc=1a0c39d317491038550071446e006ea2525ded8a7dd6512bc9152497e74d5c',
        }
        print(i)
        retry_count = 20
        while retry_count > 0:
            proxy_info = get_proxy()
            proxy = proxy_info.get("proxy")
            try:
                proxies = {
                    "http": f"http://{proxy}",
                    "https": f"http://{proxy}"
                }
                response = requests.post('https://www.qcc.com/api/datalist/rjzzqlist',
                                         cookies=cookies, headers=headers, json=json_data, proxies=proxies, timeout=20)
                time.sleep(random.uniform(1, 5))
                break
            except:
                print("代理使用错误")
                delete_proxy(proxy)
                retry_count -= 1
                if retry_count == 0:
                    stop_outer = True
                    break
                continue
        if stop_outer:
            break
        if response.json()['data'] != []:
            pass
        else:
            break
        # print(response)
        data = response.json()
        if data['data'] == []:
            print(f"第{i}页没有软件著作权！")
            break
        rjzzq_list = get_rjzzquandata(data)
        write_csv_rjzzq(rjzzq_list)


def process_company(keyno):
    """处理单个公司的数据获取"""
    # if check_zhuanli(keyno):
    # start_zhunali(keyno)
    # if check_rjzzq(keyno):
    start_rjzzq(keyno)


def process_companies_threaded(keyno_list, max_workers=3):
    """使用线程池处理多个公司"""
    with concurrent.futures.ThreadPoolExecutor(max_workers=max_workers) as executor:
        executor.map(process_company, keyno_list)


def main():
    """主函数"""
    # 这里需要提供公司keyno列表
    keyno_list = [
        'dbe9d25084764d5d6a828b44862a2d1b'
    ]  # 添加需要处理的公司keyno列表
    process_companies_threaded(keyno_list)


if __name__ == "__main__":
    main()
